import time

from dht.exception import BucketFull
from dht.utils import intify


class KBucket(object):
    __slots__ = ("min","max","nodes","node_len","last")

    def __init__(self, min, max):
        self.min = min
        self.max = max
        self.nodes = []
        self.node_len = 8
        self.last = time.time()

    def append(self,node):
        if node in self.nodes:
            self.nodes.remove(node)
            self.nodes.append(node)
            self.last = time.time()
        else:
            if len(self) < self.node_len:
                self.nodes.append(node)
                self.last = time.time()
            else:
                raise BucketFull

    def remove(self, node):
        self.nodes.remove(node)

    def in_range(self, target):
        return self.min <= intify(target) < self.max

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, node):
        return node in self.nodes

    def __iter__(self):
        for node in self.nodes:
            yield node

    def __lt__(self, target):
        return self.max <= target
